import React, { useState, useEffect, useRef } from 'react';
import { marked } from 'marked';
import axios from 'axios'; // Assuming you'll use axios for API calls

// Import theme from your theme store (you'll need to implement this in React)
// This is a simplified version of what might be in your theme store
const useThemeStore = () => {
  const [theme, setTheme] = useState({
    fillWhite: '#FFFFFF',
    textColorGrey: '#333333',
    fillBlueLight: 'rgba(92, 178, 255, 0.3)',
    textColor: '#333333',
    textColorLighten: '#666666',
    shadowColor: 'rgba(0, 0, 0, 0.1)'
  });

  const setCount = (email) => {
    // Implementation for setting count based on email
    console.log('Email set:', email);
  };

  return { theme, setCount };
};

// Utility functions
const utils = {
  getUrlParam: () => {
    const params = {};
    const search = window.location.search.substring(1);
    const pairs = search.split('&');
    
    for (let i = 0; i < pairs.length; i++) {
      const pair = pairs[i].split('=');
      params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
    }
    
    return params;
  },
  
  setCheckDomColor: (selector, property, value) => {
    const element = document.querySelector(selector);
    if (element) {
      element.style[property] = value;
    }
  },
  
  phoneReg: (text, requestId) => {
    // Replace with your phone regex implementation
    return text;
  }
};

const AssistantChat = () => {
  const themeStore = useThemeStore();
  const themeColor = themeStore.theme;
  
  // State
  const [state, setState] = useState({
    messageList: [],
    consultationList: []
  });
  
  const scrollContainer = useRef(null);
  
  // Format file size
  const formatFileSize = (size) => {
    if (size < 1024) {
      return `${size} B`;
    } else if (size < 1024 * 1024) {
      return `${(size / 1024).toFixed(2)} KB`;
    } else if (size < 1024 * 1024 * 1024) {
      return `${(size / (1024 * 1024)).toFixed(2)} MB`;
    } else {
      return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
    }
  };

  // Get file details
  const getFileDetails = (item) => {
    return new Promise((resolve) => {
      if (item.resourceFile && item.fileId) {
        let urls = item.resourceFile.split(",");
        let ids = item.fileId.split(",");
        let docList = [];
        
        for (let i = 0; i < urls.length; i++) {
          const url = urls[i];
          fetch(url, {
            method: "HEAD", // Only get file header info
          })
            .then((response) => {
              // Get file size (Content-Length header)
              const fileSize = response.headers.get("Content-Length");
              // Extract filename from URL
              const fileName = url.substring(url.lastIndexOf("/") + 1);
              docList.push({
                fileName: fileName.includes('_') ? fileName.substring(0, fileName.lastIndexOf('_')) : fileName,
                fileSize: formatFileSize(Number(fileSize)),
                fileUrl: url,
                fileId: ids[i],
                fileType: fileName.split('.').pop().toLowerCase(), // Document type
              });
              
              if (docList.length === urls.length) {
                resolve(docList);
              }
            })
            .catch((error) => {
              console.error("Unable to get file information", error);
            });
        }
      }
    });
  };

  // Get message list
  const getMessageList = async (id) => {
    try {
      const res = await axios.get(process.env.REACT_APP_BASE_API_URL + "/wechatApi/getSessionQAList", {
        params: {
          requestId: id,
          sessionId: ''
        }
      });
      
      if (res.data.code === 200) {
        setState(prevState => ({ ...prevState, messageList: res.data.data }));
        console.log(res.data.data);
        
        const updatedData = [...res.data.data];
        
        if (res.data.data[0].questionType === 4 || res.data.data[0].questionType === 1) {
          updatedData.unshift({
            text: res.data.data[0].questionContent,
            type: 0
          });
        }
        
        if (res.data.data[0].questionType === 6) {
          updatedData.unshift({
            text: res.data.data[0].questionContent,
            img: res.data.data[0].resourceFile,
            type: 6
          });
        }
        
        if (res.data.data[0].questionType === 7) {
          const list = await getFileDetails(res.data.data[0]); 
          updatedData.unshift({
            text: res.data.data[0].questionContent,
            fileList: list,
            type: 7
          });
        }
        
        setOldSession(updatedData);
      }
    } catch (error) {
      console.error("Error fetching message list:", error);
    }
  };

  // Set old session
  const setOldSession = (data) => {
    let list = [...data];
    let classification = [];
    
    for (let j = 0; j < list.length; j++) {
      let i = list[j];
      if (i.type === 1 || i.questionType === 1) {
        let arr = i.classContent?.split("|") || [];
        
        for (let j = 0; j < arr.length; j++) {
          arr[j] = arr[j].replace(/all/g, "**联系人**");
          arr[j] = utils.phoneReg(arr[j], arr[j].requestId);
          let seconed = marked(arr[j]);
          arr[j] = seconed;
        }
        
        classification = arr;
        let html = i.answerContent;
        html = utils.phoneReg(html, i.requestId) || html;
        
        if (classification.length > 0) {
          i.classification = classification;
        }
        
        i.answerContent = marked(html);
        i.answerRaw = JSON.parse(i.answerRaw);
        i.printEnd = true;
        i.activeNames = [];
        i.activeNames1 = [];
      }
    }
    
    setState(prevState => ({ ...prevState, consultationList: list }));
    console.log(list);
    window.scrollTo(0, document.body.scrollHeight);
  };

  // Check if mobile
  const isMobile = () => {
    const userAgent = navigator.userAgent.toLowerCase();
    return /iphone|ipod|android|windows phone|blackberry|bb10|mobi|xoom|tablet|mobile/i.test(
      userAgent
    );
  };

  // Handle click
  const bindClick = () => {
    if (isMobile()) {
      if (process.env.NODE_ENV === 'development') {
        // Development environment logic
      } else if (process.env.NODE_ENV === 'test') {
        window.location.href = `${process.env.REACT_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
      } else {
        window.location.href = `${process.env.REACT_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
      }
    } else {
      if (process.env.NODE_ENV === 'development') {
        // Development environment logic
      } else if (process.env.NODE_ENV === 'test') {
        window.location.href = `${process.env.REACT_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
      } else {
        window.location.href = `${process.env.REACT_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
      }
    }
  };

  useEffect(() => {
    const params = utils.getUrlParam();
    utils.setCheckDomColor(".main-container", "background", "#F1F8FE");
    
    if (params.requestId) {
      getMessageList(params.requestId);
    }
    
    if (params.email) {
      themeStore.setCount(params.email || "");
    }
    
    // Clean up function (equivalent to onUnmounted)
    return () => {
      // Any cleanup code can go here
    };
  }, []);

  // Import robot image
  const robotImage = require('../assets/images/robot1.png');
  const xleThumbnail = require('../assets/images/xleThumbnail.png');

  return (
    <div className="assistant-container">
      <div className="bg">
        <div className="top-con" id="top-con">
          <div className="header">
            <div className="header-name">
              <img onClick={bindClick} src={robotImage} alt="" />
              <span className="fs-16">小助手</span>
            </div>
            <div className="button-content" onClick={bindClick}>
              和小助手一起聊聊吧
            </div>
          </div>
        </div>
      </div>
      
      <div className="content consultation-mode" ref={scrollContainer}>
        <div className="consultation-container">
          {state.consultationList.map((item, index) => (
            <React.Fragment key={index}>
              {(item.type === 0 || item.type === 6 || item.type === 7) && (
                <div className="item itema">
                  <div className="con">
                    <div 
                      className="con-text fs-16" 
                      dangerouslySetInnerHTML={{ __html: item.text }}
                    />
                  </div>
                  
                  {item.type === 6 && (
                    <div className="img-qa">
                      <img src={item.img} alt="User uploaded content" />
                    </div>
                  )}
                  
                  {item.type === 7 && (
                    <div className="file-qa">
                      <div className="uploadImg">
                        {item.fileList.map((file, fileIndex) => (
                          <div className="img" key={fileIndex}>
                            {/* File thumbnail */}
                            <img className="img-thumbnail" src={xleThumbnail} alt="File thumbnail" />
                            {/* File description */}
                            <span className="img-info">
                              <div className="img-name">{file.fileName}</div>
                              <div className="img-size">
                                <div>{file.fileType}</div>
                                <div>{file.fileSize}</div>
                              </div>
                            </span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}
              
              {(item.type === 1 || item.questionType) && (
                <div className="item itemb">
                  <div className="ai-icon">
                    <img className="avatar" src={robotImage} alt="Assistant" />
                    <span>小助手</span>
                  </div>
                  <div className="con">
                    <div 
                      className="con-text fs-16" 
                      dangerouslySetInnerHTML={{ __html: item.answerContent }}
                    />
                  </div>
                </div>
              )}
            </React.Fragment>
          ))}
        </div>
      </div>
      
      <style jsx>{`
        .bg {
          width: 1900px;
          background-size: cover;
          height: 60px;
          border-radius: 60px;
          margin: 10px auto;
          background: linear-gradient(152.42deg,
              rgba(92, 178, 255, 1) 17.78%,
              rgba(255, 177, 177, 1) 100%);
        }

        .assistant-container {
          background: #F1F8FE;
          height: 100vh;
          overflow: hidden;
        }

        .content {
          display: flex;
          width: 100%;
          margin-top: 24px;
          flex-direction: column;
          background: ${themeColor.fillWhite};
          padding: 0 30px;
          border-radius: 24px;
        }

        .content.consultation-mode {
          background: none;
          padding: 0;
          border-radius: 0;
          border-radius: 20px;
          overflow-y: scroll;
          margin: 30px auto;
          z-index: 100;
          width: 1086px;
          height: 865px;
          position: relative;
        }

        .content.consultation-mode::-webkit-scrollbar {
          display: none;
        }

        .consultation-container {
          display: flex;
          flex-direction: column;
        }

        .item.itemb {
          flex-direction: column;
          position: relative;
        }

        .item.itemb .ai-icon {
          display: flex;
          align-items: center;
          margin-bottom: 24px;
        }

        .item.itemb .ai-icon span {
          font-size: 16px;
          font-weight: 500;
          color: ${themeColor.textColorGrey};
          line-height: initial;
          margin-left: 10px;
          vertical-align: bottom;
        }

        .item.itemb .avatar {
          width: 30px;
          margin: 0;
        }

        .item.itemb .con {
          border-radius: 14px;
          background: ${themeColor.fillWhite};
          box-shadow: 0px 0px 4px ${themeColor.fillBlueLight};
        }

        .item.itema {
          display: flex;
          flex-direction: column;
          justify-content: flex-end;
        }

        .item.itema .img-qa {
          text-align: right;
          width: 100%;
          overflow: hidden;
        }

        .item.itema .img-qa img {
          max-width: 60%;
          max-height: 400px;
          height: auto;
          width: auto;
          object-fit: contain;
          border-radius: 14px;
          padding: 14px 20px;
          background-color: rgba(92, 178, 255, 0.30);
        }

        .item.itema .file-qa .uploadImg {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          justify-content: flex-end;
          margin-bottom: 14px;
        }

        .item.itema .file-qa .uploadImg .img {
          width: 205px;
          height: 50px;
          padding: 10px;
          border-radius: 10px;
          position: relative;
          border: 1px solid #e7e7e7;
          background-color: #fff;
          display: flex;
          flex-direction: row;
          gap: 8px;
        }

        .item.itema .file-qa .uploadImg .img .img-thumbnail {
          width: 30px;
          height: 30px;
          border-radius: 5px;
          object-fit: cover;
        }

        .item.itema .file-qa .uploadImg .img .img-info {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 100%;
        }

        .item.itema .file-qa .uploadImg .img .img-info .img-name {
          color: #000;
          font-family: "PingFang SC";
          font-size: 12px;
          font-style: normal;
          font-weight: 400;
          max-width: 125px;
          line-height: normal;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .item.itema .file-qa .uploadImg .img .img-info .img-size {
          display: flex;
          gap: 5px;
          align-items: center;
        }

        .item.itema .file-qa .uploadImg .img .img-info .img-size div {
          color: #999;
          font-family: "PingFang SC";
          font-size: 10px;
          font-style: normal;
          font-weight: 400;
          line-height: normal;
        }

        .item.itema .con {
          border-radius: 14px;
          margin: 30px 0 20px auto;
          background: rgba(92, 178, 255, 0.3);
          color: #333;
        }

        .item {
          display: flex;
          justify-content: flex-end;
          margin-top: 40px;
        }

        .item:first-child {
          margin-top: 0;
        }

        .item .module-type {
          margin-top: 24px;
        }

        .item .module-type span {
          margin-right: 24px;
          font-size: 28px;
          font-weight: 500;
          letter-spacing: 0px;
          line-height: 58px;
          color: rgba(148, 162, 176, 1);
          padding: 16px 50px;
          border-radius: 220px;
          background: rgba(240, 241, 242, 1);
        }

        .item .module-type span.active {
          background: rgba(219, 238, 255, 1);
          color: #5cb2ff;
        }

        .item .avatar {
          margin-left: 16px;
          width: 51.6px;
          margin-right: 16px;
        }

        .item .con {
          max-width: 100%;
          display: flex;
          flex-direction: column;
          padding: 14px 20px;
          border-radius: 24px;
          color: ${themeColor.textColor};
          font-size: 28px;
          overflow: hidden;
        }

        .item .con .con-text {
          overflow: hidden;
        }

        .item .con .con-text ref {
          color: #999;
        }

        .item .con .con-text .docname {
          font-size: 24px;
          color: ${themeColor.textColor};
        }

        .item .con .con-text span {
          font-size: 28px;
        }

        .item .con .con-file {
          display: flex;
          flex-direction: column;
          margin-top: 20px;
          gap: 6px;
        }

        .item .con .con-file .fromto {
          color: ${themeColor.textColorLighten};
        }

        .item .con .con-file .file-item {
          margin: 4px 0px;
          word-break: break-all;
          color: ${themeColor.textColor};
        }

        .item .con .con-file .file-item.active {
          color: #5cb2ff;
        }

        .item .con .con-file .file-item div:last-child {
          margin-top: 20px;
        }

        .item .con .con-file .file-item a {
          text-decoration: underline;
          color: #5cb2ff;
        }

        .item .con .con-file .file-item .iconfont {
          color: #5cb2ff;
          margin-right: 4px;
        }

        .item .con .con-opt {
          display: flex;
          justify-content: space-between;
          padding: 18px 0 0 0;
        }

        .item .con .con-opt .left img {
          width: 36px;
          margin-right: 45px;
        }

        .item .con .con-opt .left span {
          margin-left: 68px;
        }

        .item .con .con-opt .left span:first-child {
          margin-left: 0;
        }

        .item .con .con-opt .left span.icon-good-a-copy,
        .item .con .con-opt .left span.icon-quxiaodianzan-a-copy {
          color: #e97600;
        }

        .item .con .con-opt .right img {
          width: 36px;
          margin-left: 45px;
        }

        .item:nth-child(2n) {
          justify-content: flex-start;
        }

        .item:nth-child(2n) .avatar {
          margin-left: 16px;
        }

        .top-con {
          display: flex;
          align-content: center;
          height: 100%;
          margin: 0 10px 0 30px;
        }

        .top-con .header {
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 16px;
          font-weight: 900;
          letter-spacing: 0px;
          z-index: 2;
          color: #ffffff;
        }

        .top-con .header .header-name {
          display: flex;
          gap: 20px;
        }

        .top-con .header .header-name img {
          width: 35px;
          object-fit: contain;
        }

        .top-con .header > div {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 40px;
        }

        .top-con .header .button-content {
          height: 70%;
          width: 240px;
          border-radius: 50px;
          background: #fff;
          color: #000;
          border: #F1F8FE 4px solid;
        }
      `}</style>
    </div>
  );
};

export default AssistantChat;